package com.xmg.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @Author: mazhongqing
 * @Date: 2020/11/4 15:05
 * 自定义全局返回数据增强类，将controller中的返回对象进行二次包装成统一数据格式
 * @RestControllerAdvice-->RestController
 * @ControllerAdvice-->Controller
 */
@RestControllerAdvice(basePackages = {"com.xmg.controller"})
public class ResponseControllerAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> aClass) {
        //如果接口返回的类型本身就是ResultVO，那就没有必要进行额外的操作，返回false
        return !returnType.getParameterType().equals(ResultVO.class);
    }

    @Override
    public Object beforeBodyWrite(Object data, MethodParameter returnType, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        //String类型不能直接包装，所以要进行特殊处理
        if(returnType.getParameterType().equals(String.class)){
            ObjectMapper objectMapper = new ObjectMapper();
            //将string封装成ResultVO
            try {
                return objectMapper.writeValueAsString(new ResultVO<>(data));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            //直接返回字符串
            //return data;
        }
        return new ResultVO<>(data);
    }
}
